package com.yaocw.baseproject.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class Indicator extends View {
    private Paint mForePaint;
    private Paint mBgPaint;

    int mSize;
    int mRadius;
    int mCount;
    int mOffset;
    int mActiveIdx;

    public Indicator(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public void setSize(int size) {
        mOffset = mOffset - mSize;
        mOffset = mOffset + size;

        mSize = size;
        mRadius = size;
    }

    public void setCount(int count) {
        mCount = count;
    }

    public void setOffset(int offset) {
        mOffset = mSize + offset;
    }

    public void setActiveIdx(int idx) {
        mActiveIdx = idx;
    }

    public void repaint() {
        invalidate();
    }

    private void initPaint() {
        mForePaint = new Paint();
        mForePaint.setColor(Color.RED);
        mForePaint.setAntiAlias(true);

        mBgPaint = new Paint();
        mBgPaint.setColor(Color.GRAY);
        mBgPaint.setAntiAlias(true);

        mSize = 20;
        mRadius = mSize;
        mCount = 3;
        mOffset = mSize + 20;
        mActiveIdx = 0;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (int i = 0; i < mCount; i++) {
            int x = mSize + i * (mSize + mOffset);
            int y = mSize;
            canvas.drawCircle(x, y, mRadius, mBgPaint);
        }

        int x = mSize + mActiveIdx * (mSize + mOffset);
        int y = mSize;
        canvas.drawCircle(x, y, mRadius, mForePaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);

        int w = widthSpecSize;
        int h = heightSpecSize;

        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            w = ((mSize + mOffset) * mCount) - mOffset + mSize;
            h = mSize + mSize;
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            w = ((mSize + mOffset) * mCount) - mOffset;
            h = heightSpecSize;
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            w = widthSpecSize;
            h = mSize + mSize;
        }

        setMeasuredDimension(w, h);
    }
}
